<?php

	// +----------------------------------------------------------------------
	// | 标签
	// +----------------------------------------------------------------------
	// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
	// +----------------------------------------------------------------------
	// | Author: 微尘 <yicmf@qq.com>
	// +----------------------------------------------------------------------

	namespace app\common\event;

	use app\common\event\Base;
	use think\Exception;
	use think\facade\Cache;
	use think\facade\Config;
	use think\facade\View;
	use app\common\model\Seo as SeoModel;

	class Seo extends Base
	{
		/**
		 * 生成SEO信息
		 * @param string $vars
		 * @return string
		 */
		public function buildHtml($vars = []): string
		{
			// 获取还没有经过变量替换的META信息
			$meta_seo = $this->getMeta($vars);
			$html = '<title>' . $meta_seo['title'] . '</title>
<meta name="keywords" content="' . $meta_seo['keywords'] . '"/>
<meta name="description" content="' . $meta_seo['description'] . '"/>';

			return View::display($html, $vars);
		}

		/**
		 * SEO规则 seo设置规则>setSeo()方法>seo规则无直接匹配>默认网站配置.
		 * @param array $vars
		 * @return array|mixed
		 */
		private function getMeta($vars = [])
		{
			if (isset($vars['seo'])) {
				return $vars['seo'];
			} else {
				try {
					// 查询缓存，如果已有，则直接返回;
					$module =request()->auth_module;
					$cacheKey = 'seo_meta_' . $module . '_' . $this->request->controller() . '_' . $this->request->action();
					if (!app()->isDebug() && Cache::has($cacheKey)) {
						return Cache::get($cacheKey);
					}
					$rule = SeoModel::where('status', 1)
						->whereRaw("( `module` = '' OR `module` = :module )  AND ( `controller` = '' OR `controller` = :controller )  AND ( `action` = '' OR `action` = :action )  AND `status` = 1",
							['module' => $module, 'action' => $this->request->action(), 'controller' => $this->request->controller()])
						->order('matching_degree DESC')
						->find();
					if ($rule) {
						// 存在完整匹配按照seo设置规则;
						$result = [
							'title' => $rule['seo_title'],
							'keywords' => $rule['seo_keywords'],
							'description' => $rule['seo_description'],
						];
					} else {
						// 默认站点信息
						$result = [
							'title' => Config::get('setting.web_site_title'),
							'keywords' => Config::get('setting.web_site_keywords'),
							'description' => Config::get('setting.web_site_description')
						];
					}
					Cache::set($cacheKey, $result, 3600);
				} catch (Exception $e) {
					// 默认站点信息
					$result = [
						'title' => Config::get('setting.web_site_title'),
						'keywords' => Config::get('setting.web_site_keywords'),
						'description' => Config::get('setting.web_site_description')
					];
				}

				return $result;

			}
		}


	}
